
import 'dart:async';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_play_time_page.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import '../media_library_index_view_model.dart';

///视频、图片设置参数页面
class PosterSettingsPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "PosterSettingsPage";

  final String diyJson;
  final String id;
  final String intoflg;
  final String picurl;

  const PosterSettingsPage({Key key, this.diyJson, this.id, this.intoflg,
    this.picurl}):super(key: key);

  @override
  _PosterSettingsPageState createState() => _PosterSettingsPageState();

  ///跳转方法
  static Future<bool> navigatorPush(
      BuildContext context, {String diyJson, String id, String intoflg, String picurl}) {
    return RouterUtils.routeForFutureResult(
      context,
      PosterSettingsPage(
        diyJson: diyJson,
        id: id,
        intoflg: intoflg,
        picurl: picurl,
      ),
      routeName: PosterSettingsPage.ROUTER,
    );
  }

}

class _PosterSettingsPageState extends BaseState<PosterSettingsPage>{
  String startDayStr = "";
  String endDayStr = "";
  DateTime startDay;
  DateTime endDay;
  String playTime = "";
  String interval = "";

  MediaLibraryIndexViewModel _viewModel;
  ValueNotifier<String> _fileNotifier;
  String _imagePath;
  @override
  void initState() {
    super.initState();
    _fileNotifier = ValueNotifier(null);
    _viewModel = MediaLibraryIndexViewModel(this);
    startDay = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY));
    startDayStr = DateUtil.getDateStrByDateTime(startDay, format: DateFormat.YEAR_MONTH_DAY);
    endDay = DateTime.fromMillisecondsSinceEpoch(startDay.millisecondsSinceEpoch
        + 14*24*3600*1000);
    endDayStr = DateUtil.getDateStrByDateTime(endDay, format: DateFormat.YEAR_MONTH_DAY);
    playTime = DateUtil.formatZHDateTime(startDayStr + " ", DateFormat.ZH_MONTH_DAY, "")  + (DateUtil.isToday(startDay.millisecondsSinceEpoch)?"(今天)":"");
    playTime += " ~ ";
    playTime += DateUtil.formatZHDateTime(endDayStr + " ", DateFormat.ZH_MONTH_DAY, "")  + (DateUtil.isToday(endDay.millisecondsSinceEpoch)?"(今天)":"");
    interval = "15天";
    _createFile();
  }

  @override
  void dispose() {
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: Column(
        children: <Widget>[
          _toTopBarWidget(),
          SizedBox(height: 20,),
          _toSingleImageWidget(),
          SizedBox(height: 30,),
          _settingsWidget(),
          SizedBox(height: 30,),
          _toConfirmWidget(),
        ],
      ),
    );
  }

  Future<bool> _withdrawFront() async {
    bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "退出后将不会保存您的操作，确认退出？",
        cancelText: "取消",
        confirmText: "确定",
        confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF());
    if(result ?? false) {
      VgToolUtils.removeAllFocus(context);
      RouterUtils.pop(context);
    }
    return false;
  }

  void _createFile() async{
    String base64Str = widget?.picurl?.split(",")[1];
    String imagePath =
        await FileUtils.createFileFromString(base64Str);
    if (StringUtils.isNotEmpty(imagePath)) {
      _fileNotifier?.value = imagePath;
    }
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return WillPopScope(
      onWillPop: _withdrawFront,
      child: VgTopBarWidget(
        isShowBack: true,
        title: "设置",
        backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        navFunction: _withdrawFront,
      ),
    );
  }

  Widget _toSingleImageWidget(){
    return ValueListenableBuilder(
      valueListenable: _fileNotifier,
      builder: (BuildContext context, String imagePath, Widget child){
        _imagePath = imagePath;
        return Container(
          height: 213,
          width: 120,
          color: Colors.black,
          child: VgCacheNetWorkImage(
              imagePath??"",
              imageQualityType: ImageQualityType.high,
              fit: BoxFit.cover,
              placeWidget: Container(color: Colors.black,)
          ),
        );
      }
    );
  }

  ///播放终端、播放天数
  Widget _settingsWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: _playTimes(),
    );
  }

  ///播放天数
  Widget _playTimes(){
    return Column(
      children: [
        GestureDetector(
          onTap: () async{
            Map<String, dynamic> resultMap = await MediaPlayTimePage.navigatorPush(context, startDay: startDay, endDay: endDay);
            if(resultMap == null){
              return;
            }
            setState(() {
              startDayStr = resultMap[MediaPlayTimePage.RESULT_START_DAY_STR];
              endDayStr = resultMap[MediaPlayTimePage.RESULT_END_DAY_STR];
              startDay = resultMap[MediaPlayTimePage.RESULT_START_DAY];
              endDay = resultMap[MediaPlayTimePage.RESULT_END_DAY];

              playTime = DateUtil.formatZHDateTime(startDayStr + " ", DateFormat.ZH_MONTH_DAY, "")  + (DateUtil.isToday(startDay.millisecondsSinceEpoch)?"(今天)":"");
              if(endDay == null){
                playTime += " ~ ";
                playTime += "永久";
                interval = "永久";
              }else if(startDayStr != endDayStr){
                playTime += " ~ ";
                playTime += DateUtil.formatZHDateTime(endDayStr + " ", DateFormat.ZH_MONTH_DAY, "");
                interval = (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1).toString() + "天";
              }else {
                interval = (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1).toString() + "天";
              }
            });
          },
          child: Container(
            height: 64,
            padding: EdgeInsets.symmetric(horizontal: 15),
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: [
                    Text(
                      "播放天数",
                      style: TextStyle(
                        fontSize: 14,
                        height: 1.2,
                        color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                      ),
                    ),
                    Spacer(),
                    Row(
                      children: <Widget>[
                        Text(
                          interval,
                          style: TextStyle(
                            color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                            fontSize: 14,
                            height: 1.2,
                          ),
                        ),
                        SizedBox(width: 9,),
                        Image.asset(
                          "images/index_arrow_ico.png",
                          width: 6,
                        )
                      ],
                    ),

                  ],
                ),
                Text(
                  playTime,
                  style: TextStyle(
                    fontSize: 11,
                    height: 1.2,
                    color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  ),
                ),
              ],
            ),
          ),
        ),
        // SizedBox(height: 14,)
      ],
    );
  }


  ///确定
  Widget _toConfirmWidget(){
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      height: 40,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      unSelectBgColor: Color(0xFF3A3F50),
      selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
        color: VgColors.INPUT_BG_COLOR,
        fontSize: 15,
      ),
      selectedTextStyle: TextStyle(
        color: Colors.white,
        fontSize: 15,
        // fontWeight: FontWeight.w600
      ),
      text: "确定",
      onTap: (){
        _doConfirm();
      },
    );
  }


  _doConfirm(){
    _viewModel.diyPoster(widget?.diyJson, widget?.id,
        widget?.intoflg, _imagePath, startDayStr, endDayStr);
  }
}